package com.bigdata.wsr.createTable.source;

import com.bigdata.wsr.createTable.bean.FieldInfo;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.*;
import java.util.List;
import java.util.Map;

@Slf4j
public class SourceTableUtil {
    public static String getTableDdl(String tableName, DataSource ds) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        String sql = "show create table %s";
        sql = String.format(sql, tableName);

        String ddl = null;
        try {
            conn = ds.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                ddl = rs.getString("create table");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, conn);
        }
        return ddl;
    }

    public static int getColumnCount(String tableName, DataSource ds) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        String sql = "select * from %s limit 1";
        sql = String.format(sql, tableName);
        int columnCount = 0;
        try {
            conn = ds.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            columnCount = rs.getMetaData().getColumnCount();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, conn);
        }
        return columnCount;
    }

    /**
     * ddl解析
     *
     * @param ddl         ddl
     * @param columnCount 列数
     * @param fieldInfos  字段信息
     * @param keyFieldMap 索引字段或者唯一键字段
     */
    public static void ddlParseToField(String ddl, int columnCount, List<FieldInfo> fieldInfos, Map<String, String> keyFieldMap) {
        String[] split = ddl.split("\\n");
        for (int i = 1; i <= columnCount; i++) {
            String perLine = split[i];
            int fieldNameLastIndex = perLine.lastIndexOf("`");
            // todo：解析字段名称
            String fieldName = perLine.substring(perLine.indexOf("`") + 1, fieldNameLastIndex);
            // todo：解析字段类型
            String perLineNonField = perLine.substring(fieldNameLastIndex + 2, perLine.length());
            int fieldTypeLastIndex;
            if (perLineNonField.contains(" ")) {
                fieldTypeLastIndex = perLineNonField.indexOf(" ");
            } else {
                fieldTypeLastIndex = perLineNonField.indexOf(",");
            }
            String fieldType = perLineNonField.substring(0, fieldTypeLastIndex);
            // todo：解析字段备注
            String fieldCommentLine = perLineNonField.substring(fieldTypeLastIndex + 1, perLineNonField.length());
            String[] comments = null;
            if (fieldCommentLine.contains("COMMENT")) {
                comments = fieldCommentLine.split("COMMENT");
            } else if (fieldCommentLine.contains("comment")) {
                comments = fieldCommentLine.split("comment");
            }
            String comment = null;
            if (comments != null) {
                comment = comments[1];
                comment = comment.substring(comment.indexOf("'") + 1, comment.lastIndexOf("'"));
            }
            fieldInfos.add(new FieldInfo(fieldName, fieldType, comment));
        }
        // todo：解析 uniqueKey
        for (int i = columnCount + 1; i < split.length - 1; i++) {
            String ddlPerLine = split[i];
//            log.info("ddlPerLine ----------> {}", ddlPerLine);
            if (ddlPerLine.contains("PRIMARY KEY") || ddlPerLine.contains("primary key")) {
                String primaryKeyField = ddlPerLine.substring(ddlPerLine.indexOf("(") + 1, ddlPerLine.lastIndexOf(")"));
                if (primaryKeyField.contains("`")) {
                    primaryKeyField = primaryKeyField.replaceAll("`", "");
                }
                keyFieldMap.put("primaryKeyField", primaryKeyField + ",is_delete_doris");
                log.info("primaryKeyField --------------------> {}", primaryKeyField);
            } else if (ddlPerLine.contains("UNIQUE KEY") || ddlPerLine.contains("unique key")) {
                String uniqueKeyField = ddlPerLine.substring(ddlPerLine.indexOf("(") + 1, ddlPerLine.lastIndexOf(")"));
                if (uniqueKeyField.contains("`")) {
                    uniqueKeyField = uniqueKeyField.replaceAll("`", "");
                }
                keyFieldMap.put("uniqueKeyField", uniqueKeyField + ",is_delete_doris");
            }
        }
        String lastLine = split[split.length - 1];
        String tableComment = "";
        if (lastLine.contains("COMMENT") || lastLine.contains("comment")) {
            tableComment = lastLine.substring(lastLine.indexOf("'") + 1, lastLine.lastIndexOf("'"));
        }
        keyFieldMap.put("tableComment", tableComment);
    }


    public static void close(ResultSet rs, Statement smt, Connection connection) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (smt != null) {
                smt.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
